import React, { useEffect, useState, useCallback } from 'react';
import { Spin, Empty, Tabs, message, List } from 'antd';
import { history } from 'umi'
import moment from 'moment';
import { GuideByServerFlag, LinkTo, TodoCard } from '@/components';
import { useRequest } from '@/hooks';
import { fetchSelfTask, getReadList, getMyApply } from '@/services/notice/homePage';
import todo_step from '@/assets/todo_step.png';
import { parseLocation } from '@/utils/utils';
import { newTabProps } from '@/utils/tab';
import useSubscribeMsg from '@/hooks/useSubscribeMsg';
import Msg from '@/hooks/useSubscribeMsg/Msg';
import { MoreBar } from '../common/TabBarExtraContent';
import styles from './index.less';

const { TabPane } = Tabs;

const Todo = () => {
    const [tabsDataSource, setTabsDataSource] = useState([
        {
            name: '我的待办',
            code: 'my_todo'
        },
        {
            name: '经我处理',
            code: 'my_handle'
        },
        {
            name: '我的申请',
            code: 'my_apply'
        },
        {
            name: '抄送我的',
            code: 'my_copy'
        }
    ]);

    const user = localStorage.getItem('user');
    const { employeeCode, firstOrgInfo = {} } = user ? JSON.parse(user) : {};
    const { firstCompanyCode: organizationCode } = firstOrgInfo;

    const resolveData = (result = {}) => {
        const { code, data, msg } = result;
        if (code === 10000) {
            return data;
        }
        message.error(msg);
        return null;
    };

    // 获取我的待办
    const { run: getSelfTask } = useRequest(() => fetchSelfTask({ pageNo: 1, pageSize: 10, taskStatus: 0 }), {
        manual: true,
        onSuccess: result => {
            const data = resolveData(result);
            if (data) {
                const { pageInfo = {} } = data;
                const my_todo = tabsDataSource.map(item => {
                    const temp = { ...item };
                    if (temp.code === 'my_todo') {
                        return {
                            ...temp,
                            ...pageInfo
                        };
                    }
                    return temp;
                });
                setTabsDataSource(my_todo);
            }
        }
    });

    const { run: getSelfReadList } = useRequest(
        () =>
            getReadList({
                pageNo: 1,
                pageSize: 10,
                employeeCode,
                organizationCode,
                readFlag: 0
            }),
        {
            manual: true,
            onSuccess: result => {
                const data = resolveData(result);
                if (data) {
                    const my_todo = tabsDataSource.map(item => {
                        const temp = { ...item };
                        if (temp.code === 'my_copy') {
                            return {
                                ...temp,
                                ...data
                            };
                        }
                        return temp;
                    });
                    setTabsDataSource(my_todo);
                }
            }
        }
    );

    const { run: getSelfAuditedList } = useRequest(() => fetchSelfTask({ pageNo: 1, pageSize: 10, taskStatus: 5 }), {
        manual: true,
        onSuccess: result => {
            const data = resolveData(result);
            if (data) {
                const { pageInfo = {} } = data;
                const my_todo = tabsDataSource.map(item => {
                    const temp = { ...item };
                    if (temp.code === 'my_handle') {
                        return {
                            ...temp,
                            ...pageInfo
                        };
                    }
                    return temp;
                });
                setTabsDataSource(my_todo);
            }
        }
    });

    const { run: getSelfApply } = useRequest(
        () =>
            getMyApply({
                endTime: '',
                instStatus: '',
                orderType: '',
                pageNo: 1,
                pageSize: 10,
                processDefinitionKeys: [],
                processInstanceName: '',
                startTime: ''
            }),
        {
            manual: true,
            onSuccess: result => {
                const data = resolveData(result);
                if (data) {
                    const my_todo = tabsDataSource.map(item => {
                        const temp = { ...item };
                        if (temp.code === 'my_apply') {
                            return {
                                ...temp,
                                ...data
                            };
                        }
                        return temp;
                    });
                    setTabsDataSource(my_todo);
                }
            }
        }
    );

    const moreEventHandler = (e, url) => {
        const [pathname, redirectQuery] = parseLocation({ pathname: url });
        history.push({ pathname, query: redirectQuery, ...newTabProps });
    };

    const [linkProps, setLinkProps] = useState({
        to: '/personal/todo',
        query: {},
        onClick: () => moreEventHandler(null, '/personal/todo')
    });

    const setLinkToMorePage = (url, query = {}) => {
        setLinkProps({
            to: url,
            query,
            onClick: () => moreEventHandler(null, url)
        });
    };

    const handleChange = async type => {
        switch (type) {
            case 'my_todo': {
                setLinkToMorePage('/personal/todo');
                getSelfTask();
                break;
            }
            case 'my_handle': {
                setLinkToMorePage('/personal/todo/processed');
                getSelfAuditedList();
                break;
            }
            case 'my_copy': {
                setLinkToMorePage('/personal/portal/myAuditRead/list');
                getSelfReadList();
                break;
            }
            case 'my_apply': {
                setLinkToMorePage('/personal/portal/myApplication/list');
                getSelfApply();
                break;
            }
            default:
                break;
        }
    };

    useEffect(() => {
        getSelfReadList();
        getSelfApply();
    }, [getSelfReadList, getSelfApply]);

    const getAllData = useCallback(() => {
        getSelfTask();
        getSelfAuditedList();
    }, [getSelfAuditedList, getSelfTask]);

    const { subContent } = useSubscribeMsg({ subType: [Msg.todo] });

    useEffect(() => {
        getAllData();
    }, [getAllData]);

    useEffect(() => {
        if (subContent?.type === 'todo') {
            getAllData();
        }
    }, [subContent, getAllData]);

    const renderComponents = (records = [], type) => {
        switch (type) {
            case 'my_todo': {
                return records.map(item => <TodoCard todo={item} key={`${item.id}_my_todo`} />);
            }
            case 'my_copy': {
                return (
                    <List
                        itemLayout="horizontal"
                        split={false}
                        dataSource={records}
                        renderItem={item => (
                            <List.Item key={item.id}>
                                <List.Item.Meta
                                    className={styles.workListMeta}
                                    title={
                                        <LinkTo
                                            onClick={(e, url) => {
                                                history.push(url);
                                            }}
                                            to="/personal/portal/myAuditRead/myAuditReadDetail"
                                            query={{
                                                applicationNo: item.applicationNo,
                                                processInstanceId: item.processInstanceId,
                                                id: item.id,
                                                readFlag: item.readFlag,
                                                processInstanceName: item.processInstanceName
                                            }}
                                        >
                                            {item.processInstanceName}
                                        </LinkTo>
                                    }
                                />
                                <div className={styles.wnlist_time}>
                                    {moment(item.startTime).format('YYYY-MM-DD HH:mm')}
                                </div>
                            </List.Item>
                        )}
                    />
                );
            }
            case 'my_handle': {
                return records.map(item => <TodoCard todo={item} key={`${item.id}_my_handle`} processed />);
            }
            case 'my_apply': {
                return (
                    <List
                        itemLayout="horizontal"
                        split={false}
                        dataSource={records}
                        renderItem={item => (
                            <List.Item key={item.id}>
                                <List.Item.Meta
                                    className={styles.workListMeta}
                                    title={
                                        <LinkTo
                                            onClick={(e, url) => {
                                                history.push(url);
                                            }}
                                            to="/personal/portal/myApplication/detail"
                                            query={{
                                                processInstanceId: item.processInstanceId,
                                                processInstanceName: item.processInstanceName,
                                                employeeCode
                                            }}
                                        >
                                            {item.processInstanceName}
                                        </LinkTo>
                                    }
                                />
                                <div className={styles.wnlist_time}>
                                    {moment(item.startTime).format('YYYY-MM-DD HH:mm')}
                                </div>
                            </List.Item>
                        )}
                    />
                );
            }
            default:
                return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
        }
    };

    return (
        <div className={styles.homeTodoWrapper}>
            <GuideByServerFlag.Step
                index={2}
                content={
                    <div className={styles.todoStep}>
                        <p>“待我审批”等工作任务搬到这儿啦！</p>
                        <img src={todo_step} alt="" />
                    </div>
                }
                placeholderStyle={{ height: 56 }}
                placeholderOffset={{ left: -24, width: 48 }}
                placement="topLeft"
            >
                <Tabs
                    className={styles.wnWdlcTitle}
                    onChange={handleChange}
                    tabBarExtraContent={<MoreBar linkProps={linkProps} />}
                >
                    {tabsDataSource.map(item => (
                        <TabPane
                            tab={`${item.name}${item.total && item.code !== 'my_handle' ? ` (${item.total})` : ''}`}
                            key={item.code}
                        >
                            <div className={styles.homeTodo}>
                                <Spin spinning={false}>
                                    {Array.isArray(item.rows) && item.rows.length ? (
                                        renderComponents(item.rows, item.code)
                                    ) : (
                                        <div className={styles.emptyWrapper}>
                                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                                        </div>
                                    )}
                                </Spin>
                            </div>
                        </TabPane>
                    ))}
                </Tabs>
            </GuideByServerFlag.Step>
        </div>
    );
};

export default Todo;
